#include "gifapplicationextension.h"

namespace WingGif {

int GifApplicationExtension::blockSize() { return _blockSize; }

QString GifApplicationExtension::applicationIdentifier() {
  return _applicationIdentifier;
}

QByteArray GifApplicationExtension::authenticationCode() {
  return _authenticationCode;
}

QByteArray GifApplicationExtension::data() { return _data; }

bool GifApplicationExtension::read(QIODevice *stream,
                                   QList<GifExtension *> controlExtensions) {
  Q_UNUSED(controlExtensions)
  // Note: at this point, the label (0xFF) has already been read
  auto bytes = stream->read(12);
  _blockSize = bytes[0]; // should always be 11

  if (_blockSize != 11)
    return false;

  _applicationIdentifier = bytes.mid(1, 8);
  _authenticationCode = bytes.mid(9, 3);

  char len;
  stream->read(&len, 1);
  _data = stream->read(len);

  return true;
}

GifBlockKind GifApplicationExtension::kind() {
  return GifBlockKind::SpecialPurpose;
}

GifApplicationExtension::GifApplicationExtension(QObject *parent)
    : GifExtension(parent) {}

bool GifApplicationExtension::isNetscapeExtension() {
  return _applicationIdentifier == "NETSCAPE" && _authenticationCode == "2.0";
}

ushort GifApplicationExtension::getRepeatCount() {
  if (_data.length() >= 3)
    return *reinterpret_cast<quint16 *>(_data.data() + 1);
  return 1;
}

} // namespace WingGif
